<template>
  <div class="cre-code">
    <div class="allsearch">
      <section class="search-content">
        <el-row :gutter="4" type="flex" justify="start">
          <el-col :span="22">
            <el-select v-model="value" placeholder="按优惠方式" style="width:150px;" @change="handleFilter">
              <el-option
                v-for="item in options"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              />
            </el-select>
            <el-input v-model="username" placeholder="名称关键字" style="width:250px;" @keyup.enter.native="handleFilter" />
            <el-button type="primary" @click="handleFilter">检索</el-button>
            <el-button size="medium" type="info" @click="clearParams">清空</el-button>
          </el-col>
          <el-col :span="2" >
            <div style="width:100%;">
              <el-button type="primary" style="float:right;" @click="createPromcode">生成优惠码</el-button>
            </div>
          </el-col>
        </el-row>
      </section>
      <subtable
        :table-label="codeLabel"
        :table-data="listFilter.slice((currentpage-1)*pagesize,currentpage*pagesize)"
      >
        <el-table-column slot="button" :min-width="100" label="操作" prop="manage" align="center">
          <template slot-scope="scope">
            <el-dropdown trigger="click" @command="handleCommand($event,scope)">
              <el-button type="primary">
                编辑
                <i class="el-icon-arrow-down el-icon--right"/>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="1">详情</el-dropdown-item>
                <!--<el-dropdown-item command="2">获取发放地址</el-dropdown-item>-->
                <el-dropdown-item command="3">导出csv文件</el-dropdown-item>
                <el-dropdown-item command="4">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </subtable>
      <pagination
        :total="total"
        :current-page="currentpage"
        :page-size="pagesize"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
      <!-- 优惠码详情 -->
      <el-dialog :visible.sync="dialogVisible1" :title="batchName+'优惠码使用详情'" width="980px">
        <couponList :coupon-list="couponList"/>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible1 = false">关 闭</el-button>
        </div>
      </el-dialog>
      <!-- 获取发放地址 -->
      <el-dialog :visible.sync="dialogVisible2" title="获取发放地址" width="980px">
        <el-form>
          <el-form-item label="优惠码批次">
            <el-input v-model="batchName" :disabled="true" style="width:500px;"/>
          </el-form-item>
          <el-form-item label="发 放 地 址">
            <el-input v-model="batchUrl" style="width:500px;" type="textarea" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="tag-read" style="float:left" type="primary" @click="handleCopy" >复制</el-button>
          <el-button @click="dialogVisible2 = false">关 闭</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import Clipboard from 'clipboard'
import Subtable from '@/components/Eltable'
import Pagination from '@/components/Pagination' // 分页组件
import CouponList from './createList/couponList'
import { getBatchList, deleteBatchCoupon, getCouponListByBatchId } from '@/api/operate/promcode' // 数据接口
import { parseTime } from '@/utils'
import { getTenantId } from '@/utils/auth'
export default {
  components: {
    Subtable,
    Pagination,
    CouponList
  },
  data() {
    return {
      downloadLoading: false,
      value: '',
      username: '',
      total: 0,
      currentpage: 1,
      pagesize: 10,
      dialogVisible1: false,
      dialogVisible2: false,
      listFilter: [],
      options: [{
        value: '',
        label: '全部'
      }, {
        value: '抵价',
        label: '抵价'
      }, {
        value: '打折',
        label: '打折'
      }
      ],
      codeLabel: [
        {
          label: '优惠码名称', width: '', prop: 'name'
        }, {
          label: '优惠码前缀', width: '', prop: 'prefix'
        }, {
          label: '优惠内容', width: '', prop: 'content'
        }, {
          label: '已使用/已领取/总数', width: '', prop: 'num'
        }, {
          label: '有效期', width: '', prop: 'validityTime'
        }, {
          label: '已优惠金额', width: '', prop: 'rate'
        }
      ],
      codeData: [],
      couponList: [],
      batchName: '',
      batchUrl: ''
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    handleSizeChange(val) {
      console.log(val)
      this.currentpage = 1
      this.pagesize = val.value
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    },
    handleCurrentChange(val) {
      console.log(val)
      this.currentpage = val.value
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    },
    handleFilter() {
      this.listFilter = this.codeData.filter(item => {
        if (this.value && item.wayType !== this.value) return false
        if (this.username && item.name.toLowerCase().indexOf(this.username.toLowerCase()) === -1) return false
        return true
      })
      this.total = this.listFilter.length
    },
    clearParams() {
      this.value = ''
      this.username = ''
      this.getData()
    },
    getData() {
      getBatchList('coupon').then(response => {
        this.codeData = response.data.items.filter(item => {
          if (item.tenantId !== getTenantId()) return false
          return true
        })
        this.codeData.map((item) => {
          item.num = `${item.usedNum}/${item.receiveNum}/${item.number}`
          item.validityTime = `${this.formatDate(item.startTime)}~${this.formatDate(item.endTime)}`
          let unit = ''
          if (item.wayType === 'minus') {
            item.wayType = '抵价'
            unit = '元'
          } else {
            item.wayType = '打折'
            unit = '折'
          }
          item.content = `${item.wayType}${item.rate}${unit}`
          if (item.wayType === '打折') {
            item.rate = '0.00'
          }
          // item.trench = ''
          // if (item.byLink) {
          //   item.trench += '通过链接发放' + '\n'
          // }
          // if (item.byCoupon) {
          //   item.trench += '通过优惠码发放\n'
          // }
          // if (item.byWebpage) {
          //   item.trench += '通过商品详情页发放\n'
          //   item.trench += '小程序/新版微网校'
          // }
        })
        this.total = this.codeData.length
        this.listFilter = this.codeData
      })
    },
    createPromcode() {
      this.$router.push('/operate/create-prom-code')
    },
    // 表格按钮
    handleCommand(command, scope) {
      if (command === '1') {
        getCouponListByBatchId(scope.row.id).then(response => {
          response.data.items.map((item) => {
            if (item.status === 'receive') item.status = '未领取'
            if (item.status === 'unused') item.status = '未使用'
            if (item.status === 'used') item.status = '已使用'
            if (item.status === 'using') item.status = '使用中'
          })
          this.couponList = response.data.items
        })
        this.batchName = scope.row.name
        this.dialogVisible1 = true
      } else if (command === '2') {
        // this.batchName = scope.row.name
        // this.batchUrl = scope.row.url
        // this.dialogVisible2 = true
      } else if (command === '3') {
        this.downloadLoading = true
        getCouponListByBatchId(scope.row.id).then(res => {
          res.data.items.map(item => {
            if (item.status === 'receive') item.status = '未领取'
            if (item.status === 'unused') item.status = '未使用'
            if (item.status === 'used') item.status = '已使用'
            if (item.status === 'using') item.status = '使用中'
            let unit = ''
            if (item.type === 'minus') {
              item.wayType = '抵价'
              unit = '元'
            } else {
              item.wayType = '打折'
              unit = '折'
            }
            item.content = `${item.wayType}${item.rate}${unit}`
          })
          const list = res.data.items
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = ['优惠码', '类型', '状态', '使用者', '订单信息', '优惠内容', '原价', '实付', '批次名称', '领取时间', '使用时间']
            const filterVal = ['code', 'targetType', 'status', 'userName', 'orderId', 'content', 'price', 'actualPayment', 'batchName', 'receiveTime', 'orderTime']
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: 'promCodeList',
              autoWidth: true,
              bookType: 'csv'
            })
            this.downloadLoading = false
          })
        })
      } else if (command === '4') {
        this.$confirm(`永久删除这批优惠码吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteBatchCoupon(scope.row.id, 'coupon').then(reponse => {
            if (reponse.code === 200) {
              this.$notify({
                title: '成功',
                message: '优惠码已被删除',
                type: 'success',
                duration: 2000
              })
            }
            this.getData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除'
          })
        })
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'receiveTime' || j === 'orderTime') {
          return v[j] ? parseTime(v[j]) : v[j]
        } else {
          return v[j]
        }
      }))
    },
    formatDate(data) {
      return new Date((data)).toLocaleString().substring(0, 10).replace(/[\u4e00-\u9fa5]/g, '')
    },
    handleCopy() {
      // 复制地址
      new Clipboard('.tag-read', {
        text: function() {
          return this.batchUrl
        }
      })
      this.$message({
        type: 'success',
        message: '复制成功'
      })
    }
  }
}
</script>

<style lang="scss">
  .cre-code{
    .allsearch {
      margin-top: 0px;
      padding: 0;
      .search-content {
        width: 100%;
      }
      .el-table .cell{
        white-space: pre-wrap;
      }
      .el-table td:nth-child(7){
        text-align:left
      }
    }
  }

</style>
